<template>
  <!--	这个必须加否则页面整体出现下拉情况-->
  <!--	@touchmove.stop.prevent="() => {}"-->
  <gui-page ref="guiPage" :fullPage="true" :customHeader="true">
    <template v-slot:gHeader>
      <view class="header">
        <image
          class="header-back"
          src="/static/activity/fanhui btn@2x.png"
          mode="aspectFit"
          @click="goBack"
        ></image>
        <text class="header-title">{{ title }}</text>
        <view style="width: 50rpx"></view>
      </view>
    </template>
    <template v-slot:gBody>
      <view style="height: 88rpx"></view>
      <view class="gui-flex1 gui-flex gui-column">
        <swiper
          :current="currentIndex"
          @change="swiperChange"
          :style="{ height: swiperHeight + 100 + 'px', width: '750rpx' }"
        >
          <!-- 轮播项目数量对应 上面的选项标签 -->

          <swiper-item class="gui-bg-gray">
            <view class="gui-relative gui-flex gui-bg-white">
              <gui-switch-navigation-shopping
                style="width: 100%"
                :size="150"
                lineHeight="60rpx"
                :activeLineClass="['gui-xhs-red']"
                :items="categoryTabs"
                activeDirection="center"
                textAlign="center"
                :currentIndex="currentCategoryIndex"
                @change="navchangeCategories"
              >
              </gui-switch-navigation-shopping>
            </view>
            <!--									数值越大中间边距越小-->

            <view id="content-wrap1" style="padding: 0 15rpx">
              <view
                class="gui-flex gui-row gui-space-between"
                style="margin-top: 15rpx"
              >
                <view
                  class="gui-waterfall-item"
                  v-for="(lists, index1) in noteList1"
                  :key="index1"
                >
                  <view
                    :id="'waterfall2' + index1 + index2"
                    @tap="goDetail(notes)"
                    class="gui-waterfall-items gui-bg-white gui-border-radius gui-relative"
                    style="overflow: hidden; padding-bottom: 8rpx"
                    v-for="(notes, index2) in lists"
                    :key="index2"
                  >
                    <text
                      v-if="notes.noteType == 1"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >图文笔记</text
                    >
                    <text
                      v-if="notes.noteType == 2"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >视频笔记</text
                    >
                    <text
                      v-if="notes.noteType == 3"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >音乐笔记</text
                    >

                    <gui-image
                      @imgLoad="imgLoad"
                      :src="notes.firstPicture"
                      :width="355"
                    ></gui-image>
                    <view
                      class="gui-text gui-primary-text xhs-margin-top-15 xhs-font30"
                      style="color: #333333; margin-left: 16rpx"
                      ><text>{{ notes.noteTitle }}</text>
                    </view>
                    <view
                      class="gui-flex gui-row gui-space-between xhs-margin-top-15"
                    >
                      <view>
                        <image
                          style="width: 28px; height: 28px; margin-left: 16rpx"
                          class="gui-list-image ucenter-face-image"
                          :src="notes.authorAvatar"
                          mode="aspectFill"
                        ></image>
                      </view>
                      <!--														负值越小越往左-->
                      <view
                        style="
                          font-size: 24rpx;
                          color: #5a5a5a;
                          line-height: 60rpx;
                          width: 200rpx;
                        "
                      >
                        <text>{{ notes.authorName }}</text>
                        <!--															<br/>-->
                        <!--															<text style="color:#ACACAC;">{{notes.createTimeStr}}</text>-->
                      </view>

                      <view
                        style="
                          margin-right: 16rpx;
                          color: #acacac;
                          line-height: 42rpx;
                          font-size: 28rpx;
                          text-align: center;
                        "
                      >
                        <text
                          :class="[
                            'gui-icons',
                            'gui-block',
                            'ranking-lists-zan-icon',
                            notes.isUp ? 'zan-active ' : '',
                          ]"
                          >{{ notes.isUp ? "&#xe605;" : "&#xe6ad;"
                          }}<text style="color: #5a5a5a; margin-left: 5rpx">
                            {{ notes.upCount }}</text
                          >
                        </text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view style="padding: 20rpx 0">
              <gui-loadmore ref="loadmorecom1" :status="1"></gui-loadmore>
            </view>
          </swiper-item>
        </swiper>
      </view>
    </template>
  </gui-page>
</template>
<script>
import graceJS from "@/Grace6/js/grace.js";
import getWebSocketClient from "@/Grace6/js/ws";
// 模拟数据
import dataObj from "@/Grace6/demoData/data.js";
import GuiImage from "../../Grace6/components/gui-image.vue";
import graceRequestConfig from "@/custom/graceRequestConfig.js";
import commonMixin from "@/mixin/commonMinxin";
export default {
  mixins: [commonMixin],
  components: {
    GuiImage,
  },
  data() {
    return {
      showPromotion: false,
      speakerMsgs: [
        {
          title: "商务　微信: dadait24　qq: 727869402",
        },
      ],
      loaded: false,
      // 全屏 loading
      // 顶部选项卡标签
      tabs: [
        {
          id: 1,
          name: "关注",
        },
      ],
      // 顶部选项卡标签 选中选项的 索引
      currentIndex: 0,
      swiperHeight: 0,
      defaultSwiperHeight: 0,
      noteList1: [[], []],
      noteList2: [[], []],
      noteList3: [[], []],
      // 用于记录是否有 api 请求正在执行
      apiLoadingStatus1: false,
      apiLoadingStatus2: false,
      apiLoadingStatus3: false,
      page1: 1,
      page2: 1,
      page3: 1,
      loadMoreTimer1: null,
      loadMoreTimer2: null,
      loadMoreTimer3: null,
      categoryTabs: [],
      currentCategoryIndex: 0,
      isFixed: false,
      menuHeight: 60,
      starFolderId: "",
      title: "收藏列表",
      authorId: "",
      accessToken: "",
      userId: "",
    };
  },

  computed: {
    categoryNames() {
      return this.categoryTabs.map((tab) => tab.name);
    },
  },
  watch: {
    currentIndex(newVal, OldVal) {
      if (this.currentIndex != 1) {
        uni.app.checkLogin();
      }
      this.$nextTick(() => {
        //切换时刷新高度
        this.setSwiperHeight(this.currentIndex + 1);
      });
    },
  },
  methods: {
    searchNote() {
      uni.navigateTo({
        url: "/pages/search/search",
      });
    },
    //格式化时间
    formatDate(date) {},

    //点赞笔记
    upNote(notes) {
      uni.app.post("/auth/upNote", notes, "json", "", (res) => {
        console.log(res.data);
        if (res.data) {
          notes.isUp = true;
          notes.upCount++;
        } else {
          notes.isUp = false;
          notes.upCount--;
        }
      });
    },
    //图片加载成功后重新 计算高度防止高度不够无法滑动
    imgLoad() {
      this.$nextTick(() => {
        this.setSwiperHeight(this.currentIndex + 1);
      });
    },
    //计算高度
    setSwiperHeight(i) {
      var swiperHeightTimer = null;
      if (swiperHeightTimer != null) {
        clearTimeout(swiperHeightTimer);
      }
      swiperHeightTimer = setTimeout(() => {
        let element = "#content-wrap" + i.toString();
        let query = uni.createSelectorQuery().in(this);
        query.select(element).boundingClientRect();
        query.exec((res) => {
          if (res && res[0]) {
            if (
              res[0].height == 0 ||
              res[0].height < this.defaultSwiperHeight
            ) {
              this.swiperHeight = this.defaultSwiperHeight;
            } else {
              this.swiperHeight = res[0].height;
            }
            console.log("设置swiper高度:", this.swiperHeight);
          }
        });
      }, 100);
    },
    navchange: function (index) {
      this.currentIndex = index;
    },
    swiperChange: function (e) {
      var index = e.detail.current;
      this.currentIndex = index;
    },
    //进入详情
    goDetail(e) {
      let detail = "";
      if (e.noteType == 1) {
        detail = "detail";
      } else if (e.noteType == 2) {
        detail = "videoDetail";
      }
      let url = `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/notes/${detail}/${detail}?noteId=${e.noteId}&accessToken=${
        this.accessToken
      }&userId=${this.userId}`;
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let ddd = {
            hideNavBar: "1",
            hideTotalNavBar: "0",
            hideBottomSafeBar: "0",
            url,
          };
          let d = JSON.stringify(ddd);
          console.log(d, "都是对的");
          window.AndroidBridge.pushNewWebVC(d);
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.pushNewWebVC.postMessage({
            hideNavBar: "1",
            hideTotalNavBar: "0",
            hideBottomSafeBar: "0",
            url,
          });
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },
    getNotes1(isReload) {
      // console.log('我开始请求了')
      this.apiLoadingStatus1 = true;
      const that = this;
      let data = {
        starFolderId: this.starFolderId,
        limit: 10,
        offset: this.page1,
        authorId: this.authorId,
      };

      uni.app.post("/blog/note/getStarNotes", data, "json", "", (res) => {
        if (res.code == 2000) {
          console.log("getNotes1当前页" + that.page1);
          console.log("总页数" + res.data.pages);
          if (that.page1 <= res.data.pages) {
            let notes = res.data.records;
            console.log(notes, "notes");
            //填充数组[此处的 notes 数据应该来自与api接口数据]
            //数据格式见 "/data/data.js"
            for (var i = 0; i < notes.length; i++) {
              if (i % 2 == 0) {
                that.noteList1[0].push(notes[i]);
              } else {
                that.noteList1[1].push(notes[i]);
              }
            }
            this.$nextTick(() => {
              this.setSwiperHeight(1);
            });
            if (that.page1 == res.data.pages) {
              if (this.$refs.loadmorecom1) {
                this.$refs.loadmorecom1.nomore();
              }
            } else {
              that.page1 = that.page1 + 1;
              if (this.$refs.loadmorecom1) {
                this.$refs.loadmorecom1.stoploadmore();
              }
            }
            that.apiLoadingStatus1 = false;
          } else if (res.data.pages == 0) {
            that.apiLoadingStatus1 = false;
            if (this.$refs.loadmorecom1) {
              this.$refs.loadmorecom1.nomore();
            }
          }
          if (isReload) {
            uni.stopPullDownRefresh();
          }
        }
      });
    },
    navchangeCategories(index) {
      this.currentCategoryIndex = index;
      this.page2 = 1;
      this.noteList2 = [[], []];
      if (this.$refs.loadmorecom2) {
        this.$refs.loadmorecom2.stoploadmore();
      }
      // this.getNotes2(true);
    },
    goBack() {
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          window.AndroidBridge.backEvent();
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.backEvent.postMessage({});
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },
    selectCategory(index, value) {
      this.navchangeCategories(index);
    },
  },
  //下拉刷新
  onPullDownRefresh: function () {
    if (this["apiLoadingStatus" + (this.currentIndex + 1)]) {
      uni.stopPullDownRefresh();
      return;
    }
    this["page" + (this.currentIndex + 1)] = 1;
    this["noteList" + (this.currentIndex + 1)] = [[], []];
    this["getNotes" + (this.currentIndex + 1)](true);
  },
  onShow() {
    console.log("onShow");
    console.log("this.loaded" + this.loaded);
    //证明不是第一次进页面了 刷新当前页

    // if(this.loaded){
    // 	this.$nextTick(() => {
    // 		for (let i = 0; i < 3; i++) {
    // 			this['page'+(i+1)] = 1;
    // 			this['noteList'+(i+1)] = [[],[]]
    // 			this['getNotes'+(i+1)](true);
    // 		}
    // 	})
    // }

    // this.$nextTick(() => {
    //   // 因为在appvue 无法获取tabbar
    //   const wsClient = getWebSocketClient();
    //   //获取总数
    //   uni.app.getTotalUnReadCount();
    //   wsClient.onSocketMessageCallback = (res) => {
    //     if (
    //       res.handlerType == "1" ||
    //       res.handlerType == "2" ||
    //       res.handlerType == "3" ||
    //       res.handlerType == "4"
    //     ) {
    //       //点赞收藏关注
    //       uni.app.getTotalUnReadCount();
    //     }
    //     if (res.handlerType == "5") {
    //       //获取总数
    //       uni.app.getTotalUnReadCount();
    //     }
    //     if (res.handlerType == "9") {
    //       //设置角标
    //       uni.app.setMessageTabBarBadge(res.body.totalUnReadCount);
    //     }
    //   };
    // });
  },
  mounted: function () {
    var mountedTimer = null;
    if (mountedTimer != null) {
      clearTimeout(mountedTimer);
    }
    mountedTimer = setTimeout(() => {
      // 获取页面主体高度
      graceJS.getRefs("guiPage", this, 0, (ref) => {
        ref.getDomSize("guiPageBody", (e) => {
          this.swiperHeight = e.height - uni.upx2px(110) - 92.8; //导航栏高度
          this.defaultSwiperHeight = e.height - uni.upx2px(110);
        });
      });
    }, 100);
  },

  onLoad: function (e) {
    this.starFolderId = e.starFolderId;
    this.showPromotion = graceRequestConfig.showPromotion;
    this.accessToken = e.accessToken;
    this.userId = e.userId;
    this.authorId = e.authorId;
    uni.setStorageSync("token", e.token);
    console.log("token:" + e.token);
    uni.setStorageSync("userId", e.authorId);
    console.log("userId:" + e.authorId);
    this.$nextTick(() => {
      const query = uni.createSelectorQuery().in(this);
      query
        .select("#header")
        .boundingClientRect((data) => {
          if (data) {
            console.log("获取到header高度");
          }
        })
        .exec();

      // 加载数据
      console.log("初始化加载数据");
      this.getNotes1();
      this.loaded = true;

      // 数据加载后重新计算高度
      setTimeout(() => {
        this.setSwiperHeight(this.currentIndex + 1);
      }, 300);

      const user = uni.app.getStorage("user");
      console.log("user:" + JSON.stringify(user));
    });
  },
  onReachBottom: function () {
    console.log("触发底部加载事件");
    if (this.apiLoadingStatus1) {
      console.log("API正在加载中，忽略触底事件");
      return;
    }

    // 保证触底只执行一次加载
    if (this.loadMoreTimer1 != null) {
      clearTimeout(this.loadMoreTimer1);
    }

    this.loadMoreTimer1 = setTimeout(() => {
      // 检查加载状态
      if (!this.$refs.loadmorecom1) {
        console.log("加载组件不存在");
        return;
      }

      var status = this.$refs.loadmorecom1.loadMoreStatus;
      console.log("loadMoreStatus:", status);

      if (status != 0) {
        console.log("已经在加载中或者没有更多数据了");
        return null;
      }

      // 显示加载中状态
      this.$refs.loadmorecom1.loading();
      console.log("触发加载更多");

      // 加载数据
      this.getNotes1();
    }, 50);
  },
};
</script>
<style scoped>
.search-fixed-top {
  position: fixed;
  z-index: 999;
  left: 0;
  top: 0;
  width: 100%;
}

/*数值越大屏幕中边距越小 左右模块的宽度*/
.gui-waterfall-item {
  width: 355rpx;
}

.gui-waterfall-items {
  margin-bottom: 15rpx;
}

.gui-block {
  margin-top: 10rpx;
}

.header {
  height: 88rpx;
  width: 750rpx;
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20rpx;

  .header-back {
    width: 50rpx;
    height: 50rpx;
  }

  .header-title {
    height: 88rpx;
    line-height: 88rpx;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    flex: 1;
    text-align: center;
  }
}

/* #ifdef MP */
.search-icon {
  top: 100rpx !important;
  right: 280rpx !important;
}

/* #endif */

/* #ifdef APP-PLUS */
.search-icon {
  top: 80rpx !important;
  right: 120rpx !important;
}

/* #endif */
</style>
